$(document).ready(function () {

    //var tags = [[${ALL_TAGS}]];
    $('#tags').tagEditor({
        initialTags: [],
        maxLength: 20,
        maxTags: 10,
        placeholder: "输入标签",
        autocomplete: {
            delay: 0,
            position: {collision: 'flip'},
            source: tags
        },
        forceLowercase: false
    });

    var mditor = Mditor.fromTextarea(document.getElementById('md-editor'));
    mditor.on('ready', function () {
        mditor.toolbar.items = mditor.toolbar.items.slice(0, 1);
    });

    mditor.value = content;

    $('#switch-btn').on('click', function () {

    });

    $('.toggle').bootstrapToggle({
        onstyle: "primary",
        offstyle: "info",
        on: "开启",
        off: "关闭"
    });


    // 缩略图上传
    $("#dropzone").dropzone({
        url: "/admin/file/uploadImage",
        Accept: "*/*",
        contentType: 'multipart/form-data',
        filesizeBase: 1024,//定义字节算法 默认1000
        maxFilesize: '10', //MB
        fallback: function () {
            //tale.alertError('暂不支持您的浏览器上传!');
            console.log("暂不支持您的浏览器上传");
        },
        acceptedFiles: 'image/*',
        dictFileTooBig: '您的文件超过10MB!',
        dictInvalidInputType: '不支持您上传的类型',
        // maxFiles: 1,
        init: function () {

            this.on('addedfile', function (file) {
                if (this.files.length > 1) {
                    this.removeFile(this.files[0]);
                }
            });

            this.on('success', function (files, result) {

                if (result.status === 20000) {
                    var oldImage = $('#thumbImg').val();

                    if (oldImage.trim() !== '') {
                        checkIfDeleteImage(oldImage);
                    }
                    $('#thumbImg').val("http://localhost:8080/resources/obtain/image/" + result.data);
                } else if (result.status === 40000) {

                } else {

                }
            });
            this.on('error', function (a, errorMessage, result) {
                console.log(errorMessage);
            });
        }
    });

    var refreshIntervalId;

    $('#autoSave').change(function () {
        var check = $(this).prop('checked');
        if (check) {
            refreshIntervalId = setInterval(function (args) {
                saveToDraft();
            }, 60 * 1000);
        } else {
            clearInterval(refreshIntervalId);
        }
    });


    //保存到草稿
    $('#saveToDraft').on('click', function () {

        clearInterval(refreshIntervalId);
        saveToDraft();
    });

    $('#publicBlog').on('click', function () {
        clearInterval(refreshIntervalId);
        publicBlog();
    });


    $('#tipModal').on('hidden.bs.modal', function (e) {
        $('#modalTitle').html("提示");
        $('#modalContent').html("");
        $('#modalButton').attr('href', '#');
        $('#modalButton').attr('data-dismiss', 'modal');
    });


    function showModal(content, title) {
        if (title != null) {
            $('#modalTitle').html(title);
        }
        $('#modalContent').html(content);
        $("#tipModal").modal('show');
    }

    function checkIfDeleteImage(url) {
        $.post({
            async: true,
            url: '/admin/file/deleteImage',
            data: {
                filename: url
            },
            success: function (result) {
                console.log(result);
            }
        });
    }

    function saveToDraft() {
        var value = mditor.value;
        $.post({
            url: '/admin/content/saveToDraft',
            data: {
                contentType: 0,//Markdown
                draftId: $('#articleId').val().trim(),
                title: $('#contentTitle').val(),
                content: value,
                articleUrl: $('#articleUrl').val()
            },
            success: function (result) {
                console.log(result);
                if (result.status === 20000) {
                    console.log(result.data.draftId);
                    $('#articleUrl').val(result.data.articleUrl);
                    $('#articleId').val(result.data.draftId);
                    showModal("保存成功");
                } else {
                    showModal(result.message);
                }
            },
            error: function () {
                showModal("服务器发生错误");
            }

        });
    }

    function publicBlog() {

        var title = $('#contentTitle').val();
        if (title.trim() === '') {
            showModal("<b>标题</b>不能不空!!!");
            return;
        }
        //$('#modalButton').attr('href', '/admin/article/articleManager');
        //$('#modalButton').attr('href', '#');
        //$('#modalButton').attr('data-dismiss', 'modal');
        //showModal('标题ddddddddddd不能不空!!!');

        console.log($('#tags').tagEditor('getTags')[0].tags);


        $.post({
            url: '/admin/content/publicBlog',
            data: {
                id: $('#articleId').val(),
                title: title,
                articleUrl: $('#articleUrl').val(),
                categoryId: $('#categoryId').val(),
                content: mditor.value,
                contentType: 0, //Markdown
                allowComment: +$('#allowComment').prop('checked'),
                allowPing: +$('#allowPing').prop('checked'),
                allowFeed: +$('#allowFeed').prop('checked'),
                imageUrl: $('#thumbImg').val(),
                access: $("input[name='radioAccess']:checked").val(),
                tags: $('#tags').tagEditor('getTags')[0].tags
            },
            success: function (result) {
                console.log(result);
                if (result.status === 20000) {
                    $('#modalButton').attr('href', '/admin/article/articleManager');
                    $('#modalButton').removeAttr('data-dismiss');
                    showModal("发布成功");
                } else {
                    showModal(result.message);
                }
            },
            error: function () {
                showModal("服务器发生错误");
            }
        });
    }
});